package com.ktjiaoyu.crm;

import com.ktjiaoyu.crm.dao.UserDao;
import com.ktjiaoyu.crm.pojo.User;
import com.ktjiaoyu.crm.service.UserService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@SpringBootTest
public class JpaTester {

    @Autowired
    private UserDao userDao;

    @Autowired
    private UserService userService;

    @Test
    public void testSave(){
        User user = new User("张贞","123",2l);
        User resultUser = userDao.save(user);
        System.out.println("新增的用户："+resultUser.getUsrName());
    }

    @Test
    public void testFind(){
        //User user = userDao.findById(1L).get();
        //System.out.println("ID为1的用户名："+user.getUsrName());
       // User user = userDao.findUserByUsrName("张贞");
        //System.out.println(user.getUsrName());
        //查询角色ID为1的用户列表
        List<User> userList = userDao.findByRoleId(1L);
        for(User user1 : userList){
            System.out.println(user1.getUsrName());
        }
    }

    @Test
    public void testPage(){
        //定义当前页、每页显示数量
        int currentPage = 0;    //页数从0开始
        int pageSize = 5;
        //构建Pageable对象
        Pageable pageable = PageRequest.of(currentPage,pageSize);
        Page<User> page = userDao.findByUsrRoleId(9L,pageable);
        List<User> userList = page.getContent();
        for (User user : userList){
            System.out.println(user.getUsrName());
        }
    }

    @Test
    public void testFindPageByMap(){
        int page=0,size=2;//分页要素
        //控制分页数据的排序，可以选择升序和降序
        Sort sort = Sort.by(Sort.Direction.DESC, "usrId");
        //控制分页的辅助类，可以设置页码、每页的数据条数、排序等
        Pageable pageable = PageRequest.of(page, size, sort);
        Map param = new HashMap();
        param.put("usrName","张贞");
        //param.put("roleId",8L); //测试一个查询条件，也可不给或给多个
        Page<User> userPager = userService.findPageByMap(param,pageable);
        System.out.println("总记录数 --------> " + userPager.getTotalElements());
        System.out.println("总页数 ----------> " + userPager.getTotalPages());
        System.out.println("当前页数 --------> " + userPager.getNumber());
        System.out.println("每页记录数 ------> " + userPager.getSize());
        System.out.println("当前记录： ------> ");
        for(User user:userPager.getContent()){//获得查询记录
            System.out.println("usrId： "+user.getUsrId());
        }
    }




    
    
}
